<template>
    <div class="container">
        <news-header></news-header>
        <template v-for="item in newsItems">
            <news-item :news-item="item" :rank="$index + 1"></news-item>
        </template>
    </div>
</template>

<style scoped>
    .container {
        width: 85%;
        margin: 0 auto;
        background-color: #f6f6ef;
    }
</style>

<script>
    import $ from 'jquery';
    import NewsHeader from './components/NewsHeader.vue';
    import NewsItem from './components/NewsItem.vue';

    export default {
        data: function () {
            return {
                newsItems: []
            };
        },
        components: {
            NewsHeader,
            NewsItem
        },
        methods: {
            get: function (url) {
                return Promise.resolve($.ajax(url));
            }
        },
        ready: function () {
            let that = this;

            that.get('https://hacker-news.firebaseio.com/v0/topstories.json')
                .then(function (stories) {
                    return Promise.all(stories.slice(0, 30).map(itemId => that.get('https://hacker-news.firebaseio.com/v0/item/' + itemId + '.json')));
                })
                .then(function (newsItems) {
                    that.newsItems = newsItems;
                })
                .catch(function (err) {
                    console.error('error occur', err);
                })
        }
    }
</script>